<?php

require_once __DIR__ . '/vendor/autoload.php';

use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;

$queue = 'worker';

// $connection = new AMQPStreamConnection('localhost', 5672, 'guest', 'guest');

// 连接broker
$connection = new AMQPStreamConnection(
    '49.232.138.70',
    5672,
    'finley',         //user
    'sfdwqdwq3crEt',   //password
    '/'
);

// 在连接内创建一个通道, 一个Connection可以包含多个Channel
$channel = $connection->channel();

// 第3个参数设置为true，表示让消息队列持久化
$channel->queue_declare($queue, false, true, false, false);

for ($i = 0; $i < 10; $i++) {
    $arr = [
        'id' => 'message_' . $i,
        'order_id' => str_replace('.', '', microtime(true)) . mt_rand(10, 99) . $i,
        'content' => 'helloweba-' . time()
    ];
    $data = json_encode($arr);
    // 设置rabbitmq 重启后也不会丢失队列，或者设置为'delivery_mode' => 2
    $msg = new AMQPMessage($data, ['delivery_mode' => AMQPMessage::DELIVERY_MODE_PERSISTENT]);

    // 第二个参数 exchange
    $channel->basic_publish($msg, '', $queue);
    echo 'Send message: ' . $data . PHP_EOL;
}

$channel->set_return_listener(function ($reply_code, $reply_text, $exchange, $routing_key, $msg) {
    echo "返回的结果是：" . $msg;
});

$channel->close();
$connection->close();

